package com.nohgun.bike.test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.SQLException;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.nohgun.bike.R;
import com.nohgun.bike.pass.HellowOverlay;
import com.nohgun.bike.pass.PassInfActivity;
import com.nohgun.bike.pass.PassMainActivity;
import com.nohgun.bike.pass.PassInfActivity.DispLocListener;

public class MapTest2 extends MapActivity {

    MapView mapView;

    MapController mapController;

    PowerManager.WakeLock mWakeLock;

    MyLocationOverlay mlOverlay;

    BackThread bh;

    static int thread_cnt = 1;

    LocationManager locationMgr = null;

    String bestProvider = "";

    private Camera mCamera;

    private CameraPreview mPreview;

    public TextView mMyLocationEditText;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        mapView.setSatellite(false); // 위성 뷰
        mapView.setTraffic(false); //예상 교통량

        mapController = mapView.getController();

        mlOverlay = new MyLocationOverlay(this, mapView);
        mapView.getOverlays().add(mlOverlay);
        mapView.getOverlays().add(new MyOverlay());

        locationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //프로바이더 중에 설정한 조건에 적합한 것을 가져온다. - 이 소스는 이부분을 사용했다

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE); // 정확도
        criteria.setPowerRequirement(Criteria.POWER_LOW); // 전원 소리량
        criteria.setAltitudeRequired(false); // 고도
        criteria.setBearingRequired(false); // ..
        criteria.setSpeedRequired(false); // 속도
        criteria.setCostAllowed(true); // 금전적 비용

        bestProvider = locationMgr.getBestProvider(criteria, true);

        /*
        if(location != null){
          //위도 / 경도 / 고도
            Log.d("###debug::PassInfActivity::location###","##############");
            Log.d("###debug::PassInfActivity::getLatitude###",String.valueOf(location .getLatitude()));
            Log.d("###debug::PassInfActivity::getLongitude###",String.valueOf(location .getLongitude()));
            Log.d("###debug::PassInfActivity::getAltitude###",String.valueOf(location .getAltitude()));
            
            GeoPoint p = new GeoPoint((int)location.getLatitude() *1000000, (int)location.getLongitude() *1000000); //위도하고 경도값을 지정함

            MapController mc = mapView.getController(); //실제좌표값을 맵뷰에 출력, 좌표값이 바뀌면 바뀐 위치를 화면에 출력
            mc.animateTo(p); // animateTo() 메소드에 매개변수로 받는다. 이곳으로 지도의 중심으로 가게 한다.

            mc.setZoom(16); //1~21 숫자가 클수록 정밀하게 표시 

            list = mapView.getOverlays(); //현재 맵에 등록된 레이어 목록을 추출해서 리스트로 참조한다.

            drawable = this.getResources().getDrawable(R.drawable.ic_launcher); //맵에 중심에 꽂아줄 이미지 생성

            if(helloOverlay ==null){
                helloOverlay = new HellowOverlay(drawable); //생성한 이미지를 HelloOverlay에 넣고 객체값을 받는다.
            }

            OverlayItem overlayItem = new OverlayItem(p, "", ""); // OverlayItem 클래스에 지도의 위.경도 값을 받은 객체 하나를 생성한다.

            helloOverlay.addOverlay(overlayItem); // 이를 받아서 helloOverlay에 추가한다. 넣게되면 list에 추가하게 되고 다추가하고 난 뒤에 populate해서 그려준다.

            list.add(helloOverlay); //리스트에 추가한다. googleMap.java에 추가.
            
            Log.d("###debug::PassInfActivity::list.size()###",String.valueOf(list.size()));
            
        }*/

        /*
        mapView.getOverlays().add(mlOverlay);
        
        mlOverlay.enableCompass();
        mlOverlay.enableMyLocation();
        
        
        //mapView.postInvalidate();
        //mlOverlay.enableCompass();
        //mlOverlay.enableMyLocation();
        
        mlOverlay.runOnFirstFix(new Runnable(){
            public void run(){
                
                Log.d("###debug::MyTes2t::runOnFirstFix 01 ###","01");
                
                GeoPoint pt = mlOverlay.getMyLocation();
                mapController.animateTo(pt); 
            }
        });

        */

        mapController.animateTo(new GeoPoint((int) (37.496638 * 1000000), (int) (127.0269 * 1000000)));
        mapController.setZoom(16);

        bh = new BackThread(thread_cnt);
        bh.setDaemon(true);
        bh.start();
        thread_cnt++;

        /*
        // Create an instance of Camera        
        mCamera = getCameraInstance();
        // Create our Preview view and set it as the content of our activity.        
        mPreview = new CameraPreview(this, mCamera);
        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(mPreview);


        final Button main_btn_stop = (Button) findViewById(R.id.main_btn_stop);
        main_btn_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {

                    Log.d("###debug::BackThread::stop ###", "01");
                    if (bh.isAlive()) {

                        Log.d("###debug::BackThread::stop ###", "02");
                        bh.interrupt();
                        //bh.destroy();
                        bh.requestStop();
                    }

                } catch (SQLException e) {

                    Log.e("", "- List<Memo> getMemoList()", e);

                }
            }

        });

        final Button main_btn_2 = (Button) findViewById(R.id.main_btn_2);
        main_btn_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Log.d("###debug::BackThread::start ###", "03");

                    Log.d("###debug::BackThread::start ###", "04");
                    bh = new BackThread(thread_cnt);
                    bh.setDaemon(true);
                    bh.start();
                    thread_cnt++;

                } catch (SQLException e) {

                    Log.e("", "- List<Memo> getMemoList()", e);

                }
            }

        });
    */
    }

    public void onResume() {
        super.onResume();
        mlOverlay.enableCompass();
        mlOverlay.enableMyLocation();
        //mLocationManager.requestLocationUpdates(mLocationProvider.getName(), 10000, 1, this);
    }

    public void onPause() {
        super.onPause();
        mlOverlay.disableCompass();
        mlOverlay.disableMyLocation();
        //mLocationManager.removeUpdates(this);
    }

    public void onDestroy() {
        super.onDestroy();
        mapView.getOverlays().remove(mlOverlay);

    }

    protected boolean isRouteDisplayed() {
        return false; //만일 액티비티가 운전 방향을 표시하고 있다면 반드시 true를 리턴해야함. 그렇지 않으면 false 리턴
    }

    class BackThread extends Thread {

        int cnt = 0;

        boolean liveFlag = false;

        public BackThread(int count) {
            super();
            cnt = count;
            liveFlag = true;
        }

        public void run() {

            Log.d("###debug::BackThread::run 01 ###", String.valueOf(cnt));

            while (liveFlag) {
                try {
                    Log.d("###debug::BackThread::run 01 ###", String.valueOf(cnt));
                    Thread.sleep(1000);
                    if (mlOverlay != null && mlOverlay.getMyLocation() != null) {
                        GeoPoint pt = mlOverlay.getMyLocation();
                        Log.d("###debug::BackThread::run 01 ###", String.valueOf(pt.getLatitudeE6()));
                        mapController.animateTo(pt);

                        float[] distance = new float[2];
                        Location location = locationMgr.getLastKnownLocation(bestProvider);

                        if (location != null) {
                            Log.d("###debug::BackThread::location 01 ###", String.valueOf(location.getLatitude()));
                            location.distanceBetween((double) (37.496638), (double) (127.026947), location.getLatitude(), location.getLongitude(), distance);
                            Log.d("###debug::BackThread::distance[0] ###", String.valueOf(distance[0]));
                            Log.d("###debug::BackThread::distance[1] ###", String.valueOf(distance[1]));

                        }
                    }
                } catch (InterruptedException e) {

                }
            }
        }

        public void requestStop() {

            Log.d("###debug::BackThread::liveFlag 01 ###", String.valueOf(cnt));
            liveFlag = false;
        }
    }

    class MyOverlay extends Overlay {

        @Override
        public void draw(Canvas canvas, MapView mapViewm, boolean shadow) {

            super.draw(canvas, mapViewm, shadow);

            Paint paint = new Paint();
            paint.setStrokeWidth(3);
            paint.setARGB(255, 255, 0, 0);

            GeoPoint pt01 = new GeoPoint((int) (37.496638 * 1000000), (int) (127.0269 * 1000000));
            Point po01 = new Point();
            GeoPoint pt02 = new GeoPoint((int) (37.556252 * 1000000), (int) (127.0069 * 1000000));
            Point po02 = new Point();

            mapViewm.getProjection().toPixels(pt01, po01);
            mapViewm.getProjection().toPixels(pt02, po02);

            canvas.drawCircle(po01.x, po02.y, 10, paint);
            canvas.drawCircle(po02.x, po02.y, 10, paint);

            canvas.drawLine(po01.x, po01.y, po02.x, po02.y, paint);

        }

    }

    class HellowOverlay extends ItemizedOverlay<OverlayItem> {

        private ArrayList<OverlayItem> alist = new ArrayList<OverlayItem>();

        public HellowOverlay(Drawable drawable) {

            super(boundCenterBottom(drawable));

        }

        @Override
        protected OverlayItem createItem(int i) {

            return alist.get(i);
        }

        @Override
        public int size() {
            // alist의 전체 개수를 구하기 위함
            return alist.size();
        }

        void addOverlay(OverlayItem overlayItem) {
            // 찍을 곳이 더 있다면 이곳에서 list에 추가해 준다.
            alist.add(overlayItem);
            //  그려준다.
            this.populate();
        }
    }

    /** Check if this device has a camera */
    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            // this device has a camera        
            return true;
        } else {
            // no camera on this device        
            return false;
        }
    }

    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance() {
        Camera c = null;
        try {
            c = Camera.open();
            // attempt to get a Camera instance    
        } catch (Exception e) {
            // Camera is not available (in use or does not exist)   
        }
        return c;
        // returns null if camera is unavailable
    }

    public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
        private SurfaceHolder mHolder;

        private Camera mCamera;

        public CameraPreview(Context context, Camera camera) {
            super(context);
            mCamera = camera;
            mHolder = getHolder();
            mHolder.addCallback(this);
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        public void surfaceCreated(SurfaceHolder holder) {
            try {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            } catch (IOException e) {
                Log.d("camera test", "Error setting camera preview: " + e.getMessage());
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) { // empty. Take care of releasing the Camera preview in your activity.    

        }

        public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
            if (mHolder.getSurface() == null) {

            }

            try {
                mCamera.stopPreview();
            } catch (Exception e) { // ignore: tried to stop a non-existent preview        

            }

            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();
            } catch (Exception e) {
                Log.d("ss", "Error starting camera preview: " + e.getMessage());
            }
        }
    }

}
